/* 
 * jsui
 * ====================================================
*/
jsui.bd = $('body')
jsui.is_signin = jsui.bd.hasClass('logged-in') ? true : false;

if( !window.console ){
    window.console = {
        log: function(){}
    }
}

/* 
 * ajax scroll
 * ====================================================
*/
if(jsui.ajaxpage == '1'){}

/* 
 * lazyload
 * ====================================================
*/
if ($('.avatar:eq(2)').data('src') || $('.thumb:first').data('src') || $('.widget_ui_posts .thumb:first').data('src') || $('.wp-smiley:first').data('src')) {
    require(['lazyload'], function() {
        $('.avatar').lazyload({
            data_attribute: 'src',
            placeholder: jsui.uri + '/image/avatar.png',
            threshold: 400
        })

        $('.thumb').lazyload({
            data_attribute: 'src',
            placeholder: jsui.uri + '/image/thumbnail.png',
            threshold: 400
        })
		
		$('.ranking .thumb').lazyload({
			data_attribute: 'src',
			placeholder: jsui.uri + '/image/thumbnail.png',
			threshold: 400
		})

        $('.widget_ui_posts .thumb').lazyload({
            data_attribute: 'src',
            placeholder: jsui.uri + '/image/thumbnail.png',
            threshold: 400
        })
		
		$('.widget_ui_pics .thumb').lazyload({
            data_attribute: 'src',
            placeholder: jsui.uri + '/image/thumbnail.png',
            threshold: 400
        })
		
		$('.comment .thumb').lazyload({
            data_attribute: 'src',
            placeholder: jsui.uri + '/image/thumbnail.png',
            threshold: 400
        })

    })
}



/* 
 * prettyprint
 * ====================================================
*/
$('pre').each(function(){
    if( !$(this).attr('style') ) $(this).addClass('prettyprint')
})

if( $('.prettyprint').length ){
    require(['prettyprint'], function(prettyprint) {
        prettyPrint()
    })
}

if( $('.widget-nav').length ){
    $('.widget-nav li').each(function(e){
        $(this).hover(function(){
            $(this).addClass('active').siblings().removeClass('active')
            $('.widget-navcontent .item:eq('+e+')').addClass('active').siblings().removeClass('active')
        })
    })
}



/* 
 * rollbar
 * ====================================================
*/
jsui.rb_qrcode = ''
if(jsui.qrcode) {
    jsui.rb_qrcode = "<li><a href=\"javascript:;\" title=\""+jsui.qrcode_text+"\"><i class=\"fa fa-qrcode\"></i></a><h6><img src=" + (jsui.qrcode? jsui.qrcode : jsui.uri+"/image/qr_weixin.png" )+ " alt=\"微信公众号\" width=\"150px\" height=\"150px\"><i></i></h6></li>"
}


jsui.bd.append('\
    <div class="m-mask"></div>\
    <div class="rollbar"><ul>'
	+jsui.rb_qrcode+
    '<li><a href="javascript:(scrollTo());"><i class="fa fa-angle-up"></i></a></li>\
    </ul></div>\
')

var scroller = $('.rollbar')
$(window).scroll(function() {
    document.documentElement.scrollTop + document.body.scrollTop > 200 ? scroller.fadeIn() : scroller.fadeOut();
})


/* 
 * bootstrap
 * ====================================================
*/
require(['bootstrap'], function(bootstrap) {
    $('.user-welcome').tooltip({
        container: 'body',
        placement: 'bottom'
    })
})


/* 
 * sign
 * ====================================================
*/
if (!jsui.bd.hasClass('logged-in')) {
    require(['signpop'], function(signpop) {
        signpop.init()
    })
}

$('.comt-area').bind('click', function(){
	$('.comt-comterinfo').show();								   
})

/* 
 * search
 * ====================================================
*/
$('.search-show').bind('click', function(){
    var sbox = $('.site-search')
    $(this).parent().toggleClass('active')
    $(this).find('.fa').toggleClass('fa-remove')
    sbox.toggleClass('active')
    if( sbox.hasClass('active') ){
        sbox.find('input').focus()
    }
})

$('.m-nav-search').bind('click', function(){
    var sbox = $('.site-search')
    //$(this).parent().toggleClass('active')
    $(this).toggleClass('fa-remove')
    sbox.toggleClass('active')
    if( sbox.hasClass('active') ){
        sbox.find('input').focus()
    }
})

/* 
 * bootstrap
 * ====================================================
*/

require(['bootstrap'], function(bootstrap) {
	var _sidebar = $('.sidebar')
	if (_sidebar) {
		if(jsui.headfixed == 1){
		var h1 = 15,
			h2 = 103
		}else{
		var h1 = 88,
			h2 = 103	
		}
		var rollFirst = _sidebar.find('.widget:eq(' + (jsui.roll[0] - 1) + ')')
		var sheight = rollFirst.height()

		rollFirst.on('affix-top.bs.affix', function() {
			rollFirst.css({
				top: 0
			})
			sheight = rollFirst.height()

			for (var i = 1; i < jsui.roll.length; i++) {
				var item = jsui.roll[i] - 1
				var current = _sidebar.find('.widget:eq(' + item + ')')
				current.removeClass('affix').css({
					top: 0
				})
			};
		})

		rollFirst.on('affix.bs.affix', function() {
			rollFirst.css({
				top: h1
			})

			for (var i = 1; i < jsui.roll.length; i++) {
				var item = jsui.roll[i] - 1
				var current = _sidebar.find('.widget:eq(' + item + ')')
				current.addClass('affix').css({
					top: sheight + h2
				})
				sheight += current.height() + 15
			};
		})

		rollFirst.affix({
			offset: {
				top: _sidebar.height(),
				bottom: $('.footer').outerHeight()
			}
		})


	}
})



var LS={get:function(a){return window.localStorage?localStorage.getItem(a):$.cookie(a)},set:function(a,b){window.localStorage?localStorage[a]=b:$.cookie(a,b)},remove:function(a){window.localStorage?localStorage.removeItem(a):$.cookie(a,void 0)}};

/* event click
 * ====================================================
 */
$('.action-like').on('click',function(){
	var current = $(this);
	var uncurrent = $(this).next();
	var pid = $(this).attr('data-pid')
	//if ( !pid || !/^\d{2,5}$/.test(pid) ) return;
	
	if( !jsui.is_signin ){
		var lslike = LS.get('_likes') || ''
		if( lslike.indexOf(','+pid+',')!==-1 ) return alert('你已表态过了！')

		if( !lslike ){
			LS.set('_likes', ','+pid+',')
		}else{
			if( lslike.length >= 160 ){
				lslike = lslike.substring(0,lslike.length-1)
				lslike = lslike.substr(1).split(',')
				lslike.splice(0,1)
				lslike.push(pid)
				lslike = lslike.join(',')
				LS.set('_likes', ','+lslike+',')
			}else{
				LS.set('_likes', lslike+pid+',')
			}
		}
	}
	if(!current.hasClass('unable')){
	$.ajax({
		url: jsui.uri + '/action/like.php',
		type: 'POST',
		dataType: 'json',
		data: {
			key: 'like',
			pid: pid
		},
		success: function(data, textStatus, xhr) {

			//if (data.error) return false;

			// if( data.type === 1 ){
			current.toggleClass('actived')
			uncurrent.toggleClass('unable')
			current.find('span').html(data.response)
			// }
		},
		error: function(xhr, textStatus, errorThrown) {
			//called when there is an error
			console.log(xhr)
		}
	});
	}else{return alert('你已表态过了！')}
			
	
})

$('.action-unlike').on('click',function(){
	var current = $(this);
	var uncurrent = $(this).prev();
	var pid = $(this).attr('data-pid')
	//if ( !pid || !/^\d{2,5}$/.test(pid) ) return;
	
	if( !jsui.is_signin ){
		var lslike = LS.get('_likes') || ''
		if( lslike.indexOf(','+pid+',')!==-1 ) return alert('你已表态过了！')

		if( !lslike ){
			LS.set('_likes', ','+pid+',')
		}else{
			if( lslike.length >= 160 ){
				lslike = lslike.substring(0,lslike.length-1)
				lslike = lslike.substr(1).split(',')
				lslike.splice(0,1)
				lslike.push(pid)
				lslike = lslike.join(',')
				LS.set('_likes', ','+lslike+',')
			}else{
				LS.set('_likes', lslike+pid+',')
			}
		}
	}
	if(!current.hasClass('unable')){
	$.ajax({
		url: jsui.uri + '/action/unlike.php',
		type: 'POST',
		dataType: 'json',
		data: {
			key: 'unlike',
			pid: pid
		},
		success: function(data, textStatus, xhr) {

			//if (data.error) return false;

			// if( data.type === 1 ){
			current.toggleClass('actived')
			uncurrent.toggleClass('unable')
			current.find('span').html(data.response)
			// }
		},
		error: function(xhr, textStatus, errorThrown) {
			//called when there is an error
			console.log(xhr)
		}
	});
	}else{return alert('你已表态过了！')}
			
	
})






$('.plinks a').each(function(){
    var imgSrc = $(this).attr('href')+'/favicon.ico'
    $(this).prepend( '<img src="'+imgSrc+'">' )
})


/* 
 * comment
 * ====================================================
*/
if (jsui.bd.hasClass('comment-open')) {
    require(['comment'], function(comment) {
        comment.init()
    })
}

/* 
 * single
 * ====================================================
*/
if (jsui.bd.hasClass('single')) {
	$(".article-content .main-content iframe").each(function(){
		  $(this).width("100%");
		  $(this).height($(this).width()*9/16);
	});
	$(".article-content .main-content embed").each(function(){
		  $(this).width("100%");
		  $(this).height($(this).width()*9/16);
	});
	$(".article-content .main-content video").each(function(){
		  $(this).width("100%");
		  $(this).height($(this).width()*9/16);
	});
	
	strToViews($(".read-number span").text());
	
	$('.action-fav').on('click',function(){
		var current = $(this);
		var act = 'fav';
		if(current.hasClass('active')){
			act = 'favx';
		}
		var pid = $(this).attr('data-id');
		if(pid > 0){
			$.ajax({
				url: jsui.uri + '/action/favorite.php',
				type: 'POST',
				dataType: 'json',
				data: {
					action: act,
					pid: pid
				},
				success: function(data) {
					var $count = current.find('span');
					if(data == '1'){
						current.addClass('active');
						current.html('<i class="fa fa-star"></i> 取消收藏 (<span>'+(Number($count.text()) + 1)+'</span>)');
						//$count.text(Number($count.text()) + 1);
					}else if(data == '2'){
						current.removeClass('active');
						current.html('<i class="fa fa-star-o"></i> 收藏 (<span>'+(Number($count.text()) - 1)+'</span>)');
						//$count.text(Number($count.text()) - 1);
					}else{
						alert('未知错误！');	
					}
				},
				error: function(xhr, textStatus, errorThrown) {
					alert('未知错误！');	
				}
			});
		}
	})
}


/* 
 * page u
 * ====================================================
*/
if (jsui.bd.hasClass('page-template-pagesuser-php')) {
    require(['user'], function(user) {
        user.init()
    })
}


/* 
 * page nav
 * ====================================================
*/
if( jsui.bd.hasClass('page-template-pagesnavs-php') ){

    $('#navs .items a').attr('target', '_blank')

    require(['bootstrap'], function(bootstrap) {
        $('#navs nav ul').affix({
            offset: {
                top: $('#navs nav ul').offset().top,
                bottom: $('.footer').height() + $('.footer').css('padding-top').split('px')[0]*2
            }
        })
    })

    if( location.hash ){
        var index = location.hash.split('#')[1]
        $('#navs nav .item-'+index).addClass('active')
        scrollTo( '#navs .items .item-'+index )
    }
    $('#navs nav a').each(function(e){
        $(this).click(function(){
            scrollTo( '#navs .items .item-'+$(this).parent().index() )
            $(this).parent().addClass('active').siblings().removeClass('active')
        })
    })
}


/* 
 * page search
 * ====================================================
*/
if( jsui.bd.hasClass('search-results') ){
    var val = $('.searchform .search-input').val()
    var reg = eval('/'+val+'/i')
    $('.excerpt h2 a, .excerpt .note').each(function(){
        $(this).html( $(this).text().replace(reg, function(w){ return '<b>'+w+'</b>' }) )
    })
}


/* 
 * phone
 * ====================================================
*/
$('.m-icon-nav.fa-bars').on('click', function(){
	if($(this).hasClass('nav-active')) $(this).removeClass('nav-active');
	else $(this).addClass('nav-active');
    jsui.bd.toggleClass('m-nav-show')
})

$('.m-mask').on('click', function(){
	$('.m-icon-nav').removeClass('nav-active');
    jsui.bd.removeClass('m-nav-show')
})



/* functions
 * ====================================================
 */
function scrollTo(name, add, speed) {
    if (!speed) speed = 300
    if (!name) {
        $('html,body').animate({
            scrollTop: 0
        }, speed)
    } else {
        if ($(name).length > 0) {
            $('html,body').animate({
                scrollTop: $(name).offset().top + (add || 0)
            }, speed)
        }
    }
}


function is_name(str) {    
    return /^[\w]{3,16}$/.test(str) 
}
function is_url(str) {
    return /^((http|https)\:\/\/)([a-z0-9-]{1,}.)?[a-z0-9-]{2,}.([a-z0-9-]{1,}.)?[a-z0-9]{2,}$/.test(str)
}
function is_qq(str) {
    return /^[1-9]\d{4,13}$/.test(str)
}
function is_mail(str) {
    return /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/.test(str)
}


$.fn.serializeObject = function(){
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

function strToViews(n){
	var len = Number(n.length);
	if(len > 4){
		n = Math.round((n /10000) * 100) / 100;
		n = n + "万";		
	}
	$(".read-number span").text(n);
}


function strToDate(str, fmt) { 
    if( !fmt ) fmt = 'yyyy-MM-dd hh:mm:ss'
    str = new Date(str*1000)
    var o = {
        "M+": str.getMonth() + 1, //月份   
        "d+": str.getDate(), //日   
        "h+": str.getHours(), //小时   
        "m+": str.getMinutes(), //分   
        "s+": str.getSeconds(), //秒   
        "q+": Math.floor((str.getMonth() + 3) / 3), //季度   
        "S": str.getMilliseconds() //毫秒   
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (str.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
